﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using up7.db.model;
using up7.db.sql;
using up7.down3.model;

namespace up7.down3.biz
{
    public class DnFile
    {
        static public DnFile build() { 
            return new DnFile();
        }

        public SqlTable table()
        {
            return SqlTable.build("down3_files");
        }

        public virtual void Add(DnFileInf inf)
        {
            this.table().insert(inf);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fid"></param>
        public virtual void Delete(string fid, string uid)
        {
            this.table().delete(SqlWhere.build()
                .eq("f_id", fid)
                .eq("f_uid", uid));
        }

        public virtual void process(string fid, string uid, string sizeLoc, string perLoc)
        {
            this.table().update(SqlSeter.build()
                .set("f_sizeLoc", sizeLoc)
                .set("f_perLoc", perLoc)
                , SqlWhere.build()
                .eq("f_id", fid)
                .eq("f_uid", uid));
        }

        public virtual void Clear()
        {
            this.table().clear();
        }

        /// <summary>
        /// 列出未下载完的任务
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public virtual string all_uncmp(string uid)
        {
            var files = this.table().reads<DnFileInf>(
                SqlWhere.build().eq("f_uid", uid)
                );
            return JsonConvert.SerializeObject(files);
        }

        /// <summary>
        /// 从up7_files表中加载所有已经上传完毕的文件
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public virtual string all_complete(string uid)
        {
            var fs = SqlTable.build("up7_files").reads<FileInf>(SqlWhere.build()
                .eq("f_uid", uid)
                .eq("f_deleted", false)
                .eq("f_complete", true)
                .eq("f_fdChild", false)
                .eq("f_scan", true));


            List<DnFileInf> files = new List<DnFileInf>();
            foreach (var f in fs)
            {
                DnFileInf d = new DnFileInf();
                d.id = Guid.NewGuid().ToString("N");
                d.f_id = f.id;
                d.fdTask = f.fdTask;
                d.nameLoc = f.nameLoc;
                d.sizeLoc = f.sizeLoc;
                d.sizeSvr = f.sizeLoc;
                d.lenSvr = f.lenSvr;
                d.pathSvr = f.pathSvr;
                d.lenLocSec = f.lenLocSec;
                d.encrypt = f.encrypt;
                d.blockSize = f.blockSize;
                d.objectKey = f.objectKey;
                d.objectUrl = f.objectUrl;
                d.object_id = f.object_id;
                files.Add(d);
            }
            return JsonConvert.SerializeObject(files);
        }
    }
}